<template>
	<el-button
		v-bind="$attrs"
		:class="[
			'nex-button',
			type && `nex-button--${type}`,
			size && `nex-button--${size}`,
			{
				'is-disabled': disabled,
				'is-loading': loading,
				'is-plain': plain,
				'is-round': round,
				'is-circle': circle,
			},
		]"
		:disabled="disabled || loading"
		@click="handleClick">
		<el-icon v-if="loading" class="is-loading">
			<component :is="loadingIcon" />
		</el-icon>
		<el-icon v-else-if="icon" class="nex-button__icon">
			<component :is="icon" />
		</el-icon>
		<span v-if="$slots.default" class="nex-button__content">
			<slot />
		</span>
	</el-button>
</template>

<script lang="ts" setup>
import { Loading } from "@element-plus/icons-vue";

defineOptions({
	name: "NexButton",
});

const props = withDefaults(
	defineProps<{
		type?: "primary" | "success" | "warning" | "danger" | "info";
		size?: "large" | "default" | "small";
		icon?: string;
		loadingIcon?: any;
		disabled?: boolean;
		loading?: boolean;
		plain?: boolean;
		round?: boolean;
		circle?: boolean;
	}>(),
	{
		type: undefined,
		size: "default",
		icon: undefined,
		loadingIcon: Loading,
		disabled: false,
		loading: false,
		plain: false,
		round: false,
		circle: false,
	}
);

const emit = defineEmits<{
	click: [event: MouseEvent];
}>();

const handleClick = (event: MouseEvent) => {
	if (props.disabled || props.loading) return;
	emit("click", event);
};
</script>

<style lang="scss" scoped>
.nex-button {
	position: relative;
	display: inline-flex;
	align-items: center;
	justify-content: center;
	padding: 8px 20px;
	font-size: 14px;
	font-weight: 500;
	line-height: 1.5;
	border-radius: 6px;
	transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
	cursor: pointer;
	user-select: none;

	&__icon {
		margin-right: 6px;
		font-size: 16px;
	}

	&__content {
		display: inline-block;
		vertical-align: middle;
	}

	&--large {
		padding: 10px 24px;
		font-size: 16px;

		.nex-button__icon {
			font-size: 18px;
		}
	}

	&--small {
		padding: 6px 16px;
		font-size: 12px;

		.nex-button__icon {
			font-size: 14px;
		}
	}

	&.is-loading {
		pointer-events: none;
		opacity: 0.8;

		.is-loading {
			margin-right: 6px;
			animation: rotating 2s linear infinite;
		}
	}

	&.is-disabled {
		cursor: not-allowed;
		opacity: 0.6;
	}

	&.is-round {
		border-radius: 20px;
	}

	&.is-circle {
		padding: 8px;
		border-radius: 50%;

		.nex-button__icon {
			margin: 0;
		}
	}
}

@keyframes rotating {
	0% {
		transform: rotate(0deg);
	}
	100% {
		transform: rotate(360deg);
	}
}
</style>
